import { StyleSheet, Text, View, ScrollView, Image, Pressable, TextInput, TouchableOpacity } from 'react-native';
import React, { useState, useEffect } from 'react';
import { useNavigation, useRoute } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import Icon from 'react-native-vector-icons/Ionicons';
import Modal from 'react-native-modal';
import { getDeviceDetails, updateDeviceAlias, unbindDeviceApi } from '~/api/deviceApi';
import { NavBarHeader, DialogModal } from '~/components';
import { px2dp, scale, width } from '~/utils/px2dp';
import { formatTimestamp } from '~/utils/formatDate';
import { deviceStore, userStore } from '~/store';

export default function DeviceInfo() {
    const { t } = useTranslation();
    const router: any = useRoute();
    const navigation: any = useNavigation();
    const { device_sn } = router.params || {};
    const [deviceInfo, setDeviceInfo] = useState<any>({});
    const [deviceAlias, setDeviceAlias] = useState('');
    const [visible, setVisible] = useState(false);
    const saveDeviceAlias = () => {
        updateDeviceAlias({
            device_sn,
            device_alias: deviceAlias,
        }).then((res) => {
            if (res.status == 1) {
                getData();
                setVisible(false);
            } else {
                Toast.show({ content: res.msg });
            }
        });
    };
    const getData = () => {
        getDeviceDetails({ device_sn }).then((res) => {
            if (res.status == 1) {
                const data = res.data;
                data.num = data.device_sn.substring(device_sn.length - 3);
                setDeviceInfo(data);
            } else {
                if (res.msg == '设备不存在,请联系客服!') {
                    Toast.show({ content: t('DeviceDetailes.t1'), layout: 'top' });
                } else {
                    Toast.show({ content: res.msg });
                }
                setDeviceInfo({});
            }
        });
    };
    const [unbindVisible, setUnbindVisible] = useState(false);
    const unbindDevice = () => {
        unbindDeviceApi({ device_sn }).then((res) => {
            setUnbindVisible(false);
            if (res.status == 1) {
                if (
                    deviceStore.device.connectedDeviceStatus == 1 &&
                    deviceStore.device.connectDevice?.device_sn == device_sn
                ) {
                    deviceStore.disConnectble();
                }
                if (userStore.autoConnectDeviceSn == device_sn) {
                    userStore.signAutoConnectDevice(''); // 清空对应的自动连接设备
                }
                navigation.goBack();
            } else {
                Toast.show({ content: res.msg });
            }
        });
    };
    // // 开启自动连接/清除
    // const autoConnectDevice = () => {
    //     if (userStore.autoConnectDeviceSn == deviceInfo.device_sn) {
    //         userStore.signAutoConnectDevice('');
    //         return;
    //     }
    //     userStore.signAutoConnectDevice(deviceInfo?.device_sn);
    // };
    useEffect(() => {
        getData();
    }, []);

    return (
        <View style={styles.container}>
            <NavBarHeader title={t('DeviceInfo.t1')} />
            <ScrollView contentContainerStyle={styles.contentStyle}>
                <View style={[styles.card, styles.row]}>
                    <Image style={styles.deviceImage} source={{ uri: deviceInfo.device_image }} resizeMode="contain" />
                    <View style={styles.info}>
                        <Text style={[styles.device_sn, { marginVertical: px2dp(12) }]}>
                            {t('BindDeviceList.t4')}：{deviceInfo.device_sn}
                        </Text>
                        <Text style={styles.device_sn}>
                            {t('BindDeviceList.t5')}：{formatTimestamp(deviceInfo.bind_time)}
                        </Text>
                        <Pressable style={[styles.row]} onPress={() => setVisible(true)}>
                            <Text style={styles.tips}>{deviceInfo.device_alias || t('DeviceDetailes.t3')}</Text>
                            <Icon name={'create-outline'} size={px2dp(40)} color={'#000'}></Icon>
                        </Pressable>
                    </View>
                </View>
                <View style={[styles.card]}>
                    <View style={[styles.list, styles.row, styles.between]}>
                        <Text style={styles.listTitle}>{t('DeviceInfo.t2')}</Text>
                        <Text style={styles.t2}>{deviceInfo.device_code}</Text>
                    </View>
                    <View style={[styles.list, styles.row, styles.between]}>
                        <Text style={styles.listTitle}>{t('DeviceInfo.t3')}</Text>
                        <Text style={styles.t2}>{deviceInfo.device_sn}</Text>
                    </View>
                    <View style={[styles.list, styles.row, styles.between]}>
                        <Text style={styles.listTitle}>{t('DeviceInfo.t4')}</Text>
                        <Text style={styles.t2}>{deviceInfo.firmware_sn}</Text>
                    </View>
                    <View style={[styles.list, styles.row, styles.between]}>
                        <Text style={styles.listTitle}>{t('DeviceInfo.t5')}</Text>
                        <Text style={styles.t2}>{deviceInfo.use_course_name}</Text>
                    </View>
                    {/* <View style={[styles.list, styles.row, styles.between]}>
                        <Text style={styles.listTitle}>{t('DeviceInfo.t6')}</Text>
                        <Pressable onPress={autoConnectDevice}>
                            <Image
                                style={styles.switchIcon}
                                resizeMode="contain"
                                source={
                                    userStore?.autoConnectDeviceSn == deviceInfo?.device_sn
                                        ? require('~/assets/device/open.png')
                                        : require('~/assets/device/close.png')
                                }
                            />
                        </Pressable>
                    </View> */}
                </View>
            </ScrollView>
            <View style={styles.bottom}>
                <TouchableOpacity style={styles.bootom_button} onPress={() => setUnbindVisible(true)}>
                    <Text style={styles.bootom_buttonText}>{t('DeviceDetailes.t19')}</Text>
                </TouchableOpacity>
            </View>
            <Modal
                isVisible={visible}
                presentationStyle="overFullScreen"
                onBackdropPress={() => setVisible(false)}
                statusBarTranslucent
                hasBackdrop>
                <View style={styles.modalContainer}>
                    <Text style={styles.modalTitle}>{t('DeviceDetailes.t20')}</Text>
                    <View style={[styles.input]}>
                        <TextInput
                            style={styles.inputStyle}
                            placeholder={t('DeviceDetailes.t21')}
                            returnKeyType={'done'}
                            value={deviceAlias}
                            maxLength={15}
                            onChangeText={(val) => {
                                setDeviceAlias(val);
                            }}
                            placeholderTextColor={'#a4a4a4'}
                        />
                    </View>
                    <TouchableOpacity style={[styles.bootom_button, styles.bt]} onPress={saveDeviceAlias}>
                        <Text style={styles.bootom_buttonText}>{t('DeviceDetailes.t22')}</Text>
                    </TouchableOpacity>
                </View>
            </Modal>
            <DialogModal
                key="unbind"
                visible={unbindVisible}
                content={t('DeviceDetailes.t23')}
                onCancel={() => setUnbindVisible(false)}
                onConfirm={unbindDevice}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
    },
    card: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        marginHorizontal: px2dp(24),
        marginTop: px2dp(24),
        borderRadius: px2dp(24),
    },
    deviceImage: {
        width: px2dp(120),
        height: px2dp(140),
    },
    info: {
        marginLeft: px2dp(24),
    },
    t1: {
        fontSize: scale(30),
        fontWeight: 'bold',
        color: '#000',
    },
    device_sn: {
        fontSize: scale(28),
        color: '#a4a4a4',
    },
    tips: {
        color: '#a4a4a4',
        fontSize: scale(28),
        marginRight: px2dp(12),
        marginTop: px2dp(12),
    },
    modalContainer: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(22),
    },
    input: {
        borderWidth: 1,
        borderColor: '#eee',
        borderRadius: px2dp(16),
        paddingHorizontal: px2dp(16),
        height: px2dp(100),
        justifyContent: 'center',
        marginTop: px2dp(16),
    },
    inputStyle: {
        color: '#000',
        fontSize: scale(28),
    },
    modalTitle: {
        color: '#000',
        textAlign: 'center',
        fontSize: scale(30),
        marginBottom: px2dp(32),
    },
    bottom: {
        paddingVertical: px2dp(60),
        position: 'absolute',
        bottom: 0,
        width: width,
    },
    bootom_button: {
        backgroundColor: '#242D56',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(999),
        height: px2dp(100),
        marginHorizontal: px2dp(32),
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    bt: {
        backgroundColor: '#242D56',
        borderColor: '#242D56',
        marginTop: px2dp(32),
    },
    list: {
        height: px2dp(80),
    },
    listTitle: {
        color: '#a4a4a4',
        fontSize: scale(28),
    },
    t2: {
        color: '#000',
        fontSize: scale(28),
    },
    switchIcon: {
        width: px2dp(120),
        height: px2dp(50),
    },
});
